package com.hnichr.ump.business.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hnichr.ump.business.Constant;
import com.hnichr.ump.common.doc.entity.Goods;
import com.hnichr.ump.common.doc.entity.GoodsType;
import com.hnichr.ump.common.doc.service.GoodsService;
import com.hnichr.ump.common.doc.service.GoodsTypeService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.system.service.impl.BaseServiceImpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;

@Service
public class GoodsTypeServiceImpl extends BaseServiceImpl<GoodsType> implements GoodsTypeService {
	@Autowired
	private GoodsService goodsService;

	@Override
	@Transactional(readOnly = false)
	public GoodsType save(GoodsType goodsType) {
		// 验证商品是否已配置过
		Criteria criteria = Criteria.create();
		criteria.addCriterion("seqNo", Operator.EQ, goodsType.getSeqNo());
		criteria.addCriterion("validFlag", Operator.EQ, Constant.STATUS_VALID);
		List<GoodsType> goodsTypes = this.list(GoodsType.class, criteria);
		if (CollectionUtil.isNotEmpty(goodsTypes)) {
			throw new RuntimeException("相同序号分类已经存在，请勿重复配置");
		}
		criteria = Criteria.create();
		criteria.addCriterion("typeName", Operator.EQ, goodsType.getTypeName());
		criteria.addCriterion("validFlag", Operator.EQ, Constant.STATUS_VALID);
		goodsTypes = this.list(GoodsType.class, criteria);
		if (CollectionUtil.isNotEmpty(goodsTypes)) {
			throw new RuntimeException("相同名称分类已经存在，请勿重复配置");
		}
		goodsType.setValidFlag(Constant.STATUS_VALID);
		super.save(goodsType);
		return goodsType;
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(String id) {

		GoodsType goodsType = JpaUtil.getOne(GoodsType.class, id);
		if (ObjectUtil.isNull(goodsType)) {
			return;
		}
		// 验证是否有商品使用此分类
		Criteria criteria = Criteria.create();
		criteria.addCriterion("goodsType", Operator.EQ, id);
		criteria.addCriterion("validFlag", Operator.EQ, Constant.STATUS_VALID);
		List<Goods> goods = goodsService.list(Goods.class, criteria);
		if (CollectionUtil.isNotEmpty(goods)) {
			throw new RuntimeException("该品类仍有商品在用，请勿删除！");
		}
		// 逻辑删除
		goodsType.setValidFlag(Constant.STATUS_INVALID);
		JpaUtil.update(goodsType);
	}
}
